/*
 * uart.c
 *
 *  Created on: 01-02-2012
 *      Author: Mateusz
 */

#include "LPC13xx.h"
#include "uart.h"

void UARTInit() {
	uint32_t regVal;

	NVIC_DisableIRQ(UART_IRQn);

	LPC_IOCON->PIO1_6 &= ~0x07; /*  UART I/O config */
	LPC_IOCON->PIO1_6 |= 0x01; /* UART RXD */
	LPC_IOCON->PIO1_7 &= ~0x07;
	LPC_IOCON->PIO1_7 |= 0x01; /* UART TXD */
	/* Enable UART clock */LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 12);
	LPC_SYSCON->UARTCLKDIV = 0x1; /* divided by 1 */

	LPC_UART->LCR = 0x83; /* 8 bits, no Parity, 1 Stop bit */

	LPC_UART->DLM = 0;
	LPC_UART->DLL = 1;
	LPC_UART->FDR = 0x81;
	LPC_UART->LCR = 0x03; /* DLAB = 0 */
	LPC_UART->FCR = 0x07; /* Enable and reset TX and RX FIFO. */

	/* Read to clear the line status. */
	regVal = LPC_UART->LSR;

	/* Ensure a clean start, no data in either TX or RX FIFO. */
	// CodeRed - added parentheses around comparison in operand of &
	while ((LPC_UART->LSR & (LSR_THRE | LSR_TEMT)) != (LSR_THRE | LSR_TEMT))
		;
	while (LPC_UART->LSR & LSR_RDR) {
		regVal = LPC_UART->RBR; /* Dump data from RX FIFO */
	}

	return;
}

void UARTSendByte(uint8_t data) {
	/* THRE status, contain valid data */
	while (!(LPC_UART->LSR & LSR_THRE))
		;
	LPC_UART->THR = data;

}
